﻿#include "RpcSocketChannelManager.h"
#include "XyNet/Common/Logger.h"
#include "XyNet/Common/SetMapHelper.h"
#include "XyNet/Channel/RpcSocketChannel.h"

namespace XyNet
{
	void RpcSocketChannelManager::addSocketChannel(shared_ptr<RpcSocketChannel> socketChannel)
	{
		SetMapHelper::insert(_socketChannelMapObject.createUniqueLock()->getObject(),
			socketChannel->getId(), socketChannel);
	}

	void RpcSocketChannelManager::removeSocketChannel(
		shared_ptr<RpcSocketChannel> socketChannel)
	{
		SetMapHelper::erase(_socketChannelMapObject.createUniqueLock()->getObject(),
			socketChannel->getId());
	}

	int RpcSocketChannelManager::getSocketChannelCount() const
	{
		return numeric_cast<int>(_socketChannelMapObject.createSharedLock()->getObject()->size());
	}

	shared_ptr<RpcSocketChannel> RpcSocketChannelManager::findSocketChannel(
		const Id& socketChannelId) const
	{
		auto lock = _socketChannelMapObject.createSharedLock();
		auto* socketChannelMap = lock->getObject();
		auto iter = socketChannelMap->find(socketChannelId);
		if (iter != socketChannelMap->end())
			return iter->second;
		else
			return nullptr;
	}

	vector<shared_ptr<RpcSocketChannel>> RpcSocketChannelManager::getSocketChannels() const
	{
		vector<shared_ptr<RpcSocketChannel>> socketChannels;
		auto lock = _socketChannelMapObject.createSharedLock();
		socketChannels.reserve(lock->getObject()->size());
		for (const auto& pair : *lock->getObject())
			socketChannels.emplace_back(pair.second);
		lock->unlock();
		return socketChannels;
	}

	vector<shared_ptr<RpcSocketChannel>> RpcSocketChannelManager::findSocketChannels(
		function<bool(shared_ptr<RpcSocketChannel>)> predicate) const
	{
		vector<shared_ptr<RpcSocketChannel>> socketChannels;
		auto lock = _socketChannelMapObject.createSharedLock();
		for (const auto& pair : *lock->getObject())
		{
			if (predicate(pair.second))
				socketChannels.emplace_back(pair.second);
		}
		lock->unlock();
		return socketChannels;
	}
}